<?php

namespace App\Traits;

use App\Models\Admin\Supplier;
use Exception;
use exceptions\SupplierDatabaseRegisterException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Connection;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 需要配合中间件supplier:withDb使用
 */
trait SupplierDbConnections
{
    /**
     * The connection name for the model.
     *
     * @var string|null
     */
    protected $connection = null;

    /**
     * @return ?string
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getConnectionName(): ?string
    {
        return $this->connection ?? request()->get('db', null);
    }

    /**
     * @param Supplier|int $supplier
     * @return Builder
     */
    static public function s(Supplier|int $supplier): Builder
    {
        return static::purveyor($supplier);
    }

    /**
     * 供应商
     *
     * @param Supplier|int $supplier
     * @return Builder
     */
    static public function purveyor(Supplier|int $supplier): Builder
    {
        return static::on(dbConnectKey($supplier));
    }

    /**
     * @param Supplier|int $supplier
     * @return Builder
     * @throws SupplierDatabaseRegisterException
     */
    static public function sr(Supplier|int $supplier): Builder
    {
        return static::purveyorRegister($supplier);
    }

    /**
     * @param Supplier|int $supplier
     * @return Builder
     * @throws SupplierDatabaseRegisterException
     */
    static public function purveyorRegister(Supplier|int $supplier): Builder
    {
        $dbKey = dbRegister($supplier);
        if (!$dbKey) {
            throw new SupplierDatabaseRegisterException($supplier);
        }
        return static::on($dbKey);
    }
}
